<template>
  <div class="tag-dropdown-container">
    <!-- 触发按钮内嵌在父组件中 -->
    
    <!-- 下拉菜单 -->
    <div v-if="visible" class="tag-dropdown" :style="{ top: top }">
      <!-- 搜索输入框 -->
      <div class="search-container">
        <el-input
          v-model="searchInput"
          placeholder="请输入标签内容..."
          maxlength="20"
          @keyup.enter="handleAddTag"
          ref="inputRef"
          autofocus
          
        >
          <template #append>
            <el-button @click="handleAddTag">添加</el-button>
          </template>
        </el-input>
      </div>
      
      <!-- 历史标签列表 -->
      <div v-if="filteredTags.length > 0" class="history-tags">
        <div class="history-title">历史标签</div>
        <div class="tags-list">
          <div 
            v-for="(tag, index) in filteredTags" 
            :key="index" 
            class="history-tag-item"
            @click.stop="selectHistoryTag(tag)"
          >
            <span class="history-tag">#{{ tag }}</span>
          </div>
        </div>
      </div>
      
      <!-- 无匹配结果时显示"添加新标签"选项 -->
      <div v-if="searchInput.trim() && !hasExactMatch" class="add-new-tag">
        <el-button type="primary" plain size="small" @click.stop="handleAddTag">
          添加「{{ searchInput }}」标签
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick, onMounted, onUnmounted } from 'vue'

// 定义props
interface Props {
  visible: boolean;
  maxHistory?: number;
  top?: string;
}

const props = withDefaults(defineProps<Props>(), {
  maxHistory: 10
})

// 定义emit
const emit = defineEmits<{
  (e: 'select', tag: string): void;
  (e: 'close'): void;
}>()

// 状态
const searchInput = ref('')
const inputRef = ref<any>(null)

// 历史标签列表
const historyTags = ref<string[]>([])

// 过滤标签
const filteredTags = computed(() => {
  const input = searchInput.value.trim().toLowerCase()
  if (!input) return historyTags.value
  
  return historyTags.value.filter(tag => 
    tag.toLowerCase().includes(input)
  )
})

// 是否有完全匹配的标签
const hasExactMatch = computed(() => {
  const input = searchInput.value.trim().toLowerCase()
  return historyTags.value.some(tag => 
    tag.toLowerCase() === input
  )
})

// 添加标签
const handleAddTag = () => {
  const tag = searchInput.value.trim()
  if (tag) {
    // 发送选择的标签
    emit('select', tag)
    
    // 保存到历史记录
    saveTagToHistory(tag)
    
    // 清空输入
    searchInput.value = ''
    
    // 关闭下拉菜单
    emit('close')
  }
}

// 选择历史标签
const selectHistoryTag = (tag: string) => {
  // 发送选择的标签
  emit('select', tag)
  
  // 更新历史记录顺序
  saveTagToHistory(tag)
  
  // 清空输入
  searchInput.value = ''
  
  // 关闭下拉菜单
  emit('close')
}

// 保存标签到历史记录
const saveTagToHistory = (tag: string) => {
  // 从localStorage加载历史标签
  const storedTags = localStorage.getItem('historyTags')
  let tags: string[] = storedTags ? JSON.parse(storedTags) : []
  
  // 移除重复的标签
  tags = tags.filter(t => t !== tag)
  
  // 添加到顶部
  tags.unshift(tag)
  
  // 限制最大数量
  if (tags.length > props.maxHistory) {
    tags = tags.slice(0, props.maxHistory)
  }
  
  // 保存回localStorage
  localStorage.setItem('historyTags', JSON.stringify(tags))
  
  // 更新组件状态
  historyTags.value = tags
}

// 加载历史标签
const loadHistoryTags = () => {
  const storedTags = localStorage.getItem('historyTags')
  historyTags.value = storedTags ? JSON.parse(storedTags) : []
}

// 点击外部关闭下拉菜单
const handleClickOutside = (event: MouseEvent) => {
  // 如果下拉菜单不可见，不处理
  if (!props.visible) return
  
  // 检查是否点击的是.topic-trigger元素或其子元素
  const topicTrigger = document.querySelector('.topic-trigger')
  if (topicTrigger && topicTrigger.contains(event.target as Node)) {
    console.log('点击了话题触发器，不关闭下拉菜单')
    return
  }
  
  const dropdown = document.querySelector('.tag-dropdown-container')
  // 如果点击的不是下拉菜单内的元素，触发关闭
  if (dropdown && !dropdown.contains(event.target as Node)) {
    console.log('点击了下拉菜单外部，关闭菜单')
    emit('close')
  }
}

// 组件显示时自动聚焦输入框
watch(() => props.visible, (newValue) => {
  if (newValue) {
    console.log('标签下拉菜单显示')
    // 加载历史标签
    loadHistoryTags()
    
    // 聚焦输入框
    nextTick(() => {
      inputRef.value?.focus()
    })
  } else {
    // 清空输入
    searchInput.value = ''
  }
}, { immediate: true })

// 初始化和清理
onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>


.tag-dropdown {
  position: absolute;
  /* top: 230%; */
  left: 0;
  width: 300px;
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 1rem;
  margin-top: 0.5rem;
  z-index: 1000;
}

.search-container {
  margin-bottom: 1rem;
}

.history-tags {
  margin-top: 1rem;
}

.history-title {
  font-size: 0.875rem;
  color: #666;
  margin-bottom: 0.5rem;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.history-tag-item {
  cursor: pointer;
  background-color: #f3f4f6;
  border-radius: 0.25rem;
  padding: 0.25rem 0.5rem;
  transition: background-color 0.2s;
}

.history-tag-item:hover {
  background-color: #e5e7eb;
}

.history-tag {
  font-size: 0.875rem;
  color: #2563eb;
}

.add-new-tag {
  margin-top: 1rem;
  border-top: 1px solid #e5e7eb;
  padding-top: 1rem;
}
</style> 